require "yaml"
require 'json'

class TCPSocket
	attr_reader :response
	
	def send raw_req
		self.write "#{raw_req}\n"
		@response = self.gets
	end
	
	def send_json action, resource, params = {}
		self.write({'action' => action, 'resource' => resource, 'params' => params}.to_json)
		@response = self.gets
	end
	
	def recv_json
		JSON.parse(@response)
	end
end

class GamesController < ApplicationController
	def connect
		TCPSocket.open('127.0.0.1', 9999) do |s|
			yield s
		end
	end
	
	def index
		respond_to do |format|
			format.html
			format.json do
				if params['request'] then
					connect do |s|
						s.send_json('POST', 'game', {'id' => current_user.room.game_id})
						s.send_json('POST', 'player', {'id' => current_user.position})
						s.send(params['request'])
						result = s.response
						
						rest_req = JSON.parse(params['request'])
						if rest_req['resource'] == 'messages' then
							puts "\[Player #{current_user.position}\]"
							result.gsub!(/\[Player #{current_user.position}\]/, 'You')
						end
						
						@json_result = result
					end
				end
			end
		end
	end
	
	def start
		connect do |s|
			s.send_json('POST', 'game', {'players' => current_user.room.max_players})
			s.send_json('GET', 'game/id')
			response = s.recv_json()
			
			if response['status'] == 200 then
				current_user.room.status = 'ingame'
				current_user.room.game_id = response['game']['id']
				
				current_user.room.save
			end
		end
		redirect_to game_path
	end
end
